package com.lesama.stream;

// 文件夹拷贝

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DirectoryCopyTest {
    public static void main(String[] args) throws IOException {
        File src = new File("D:\\test");
        File dest = new File("D:\\my");
        if(src.equals(dest)) {
            System.out.println("目标文件夹是原文件夹的子文件夹");
        } else {
            copyDir(src, dest);
        }
    }

    public static void copyDir(File src, File dest) throws IOException {
        File newDir = new File(dest, src.getName()); // 要创建的新目录
        newDir.mkdirs();
        File[] files = src.listFiles();
        for (File file : files) {
            if(file.isFile()) {
                // 文件则直接拷贝
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(new File(newDir, file.getName()));
                byte[] bys = new byte[1024];
                int len;
                while ((len = fis.read(bys)) != -1) {
                    fos.write(bys, 0, len);
                }
                fis.close();
                fos.close();
            } else {
                // 文件夹递归拷贝
                copyDir(file, newDir);
            }
        }
    }
}